import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { Observable } from "rxjs";
import { Roles } from "../decorator/roles.decorator";
import { JwtService } from "@nestjs/jwt";


@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
    private readonly jwtService: JwtService,
  ) { }

  canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {

    const roles = this.reflector.get(Roles, context.getHandler())

    // 没有设置roles，守卫放行
    if (!roles) {
      return true;
    }

    const req = context.switchToHttp().getRequest();
    const headers = this.nomalisizeHeaders(req.rawHeaders);
    const token = headers.Authorization.split('Bearer ')[1];
    const data = this.jwtService.verify(token);

    const hasCommonRole = data.roleIds.some((roleCode: string) => roles.includes(roleCode));
    return hasCommonRole;
  }

  private nomalisizeHeaders(headersArray: string[]): any {
    return headersArray.reduce((acc, curr, index) => {
      if (index % 2 === 0) {
        acc[curr] = headersArray[index + 1];
      }
      return acc;
    }, {});

  }
}